package com.wceManage.manage.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wceManage.beans.SysMenu;
import com.wceManage.commons.util.CacheUtils;
import com.wceManage.commons.util.StringUtil;
import com.wceManage.manage.util.LogUtils;
import com.wceManage.manage.util.UserUtils;
import com.wceManage.services.SysMenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "resource")
public class MenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    @ModelAttribute("sysResource")
    public SysMenu get(@RequestParam(required = false) Long id) {
        if (id != null) {
            SysMenu sysMenu = sysMenuService.queryById(id);
            return sysMenu;
        } else {
            return new SysMenu();
        }
    }

    @RequiresPermissions("sys:menu:view")
    @RequestMapping(value = {"list", ""})
    public String list(Model model) {
        List<SysMenu> list = Lists.newArrayList();
        List<SysMenu> sourcelist = UserUtils.getMenuList();
        SysMenu.sortList(list, sourcelist, SysMenu.getRootId(), true);
        model.addAttribute("list", list);
        return "sys/resource/list";
    }

    @RequiresPermissions("sys:menu:view")
    @RequestMapping(value = "form")
    public String form(SysMenu sysMenu, Model model) {

        if(sysMenu.getMenuId() != null){
            sysMenu = sysMenuService.queryById(sysMenu.getMenuId());
        }else if(sysMenu.getParent() == null){
            sysMenu.setParent(new SysMenu(SysMenu.getRootId()));
        }

        sysMenu.setParent(sysMenuService.queryById(sysMenu.getParent().getMenuId()));
        // 获取排序号，最末节点排序号+30
        if (sysMenu.getMenuId() == null) {
            List<SysMenu> list = Lists.newArrayList();
            List<SysMenu> sourcelist = UserUtils.getMenuList();
            sysMenu.sortList(list, sourcelist, sysMenu.getParentId(), false);
            if (list.size() > 0) {
                sysMenu.setOrderNum(list.get(list.size() - 1).getOrderNum() + 30);
            }
        }
        model.addAttribute("sysResource", sysMenu);
        return "sys/resource/edit";
    }

    @RequiresPermissions("sys:menu:edit")
    @RequestMapping(value = "save")
    public String save(SysMenu sysMenu) {
        sysMenu.setUserId(UserUtils.getUser().getUserId());

        sysMenuService.saveReSource(sysMenu);

        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        return "redirect:list";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "treeselect")
    public String treeselect(String parentId, Model model) {
        model.addAttribute("parentId", parentId);
        return "sys/resource/menuTreeselect";
    }

    @RequiresPermissions("sys:menu:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public Object delete(SysMenu sysMenu) {
        sysMenuService.delete(sysMenu);
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        String result = "删除菜单成功!";
//        addMessage(redirectAttributes, "删除菜单成功");
        return result;
    }

    /**
     * 批量修改菜单排序
     */
    @RequiresPermissions("sys:menu:edit")
    @RequestMapping(value = "updateSort")
    public String updateSort(Long[] ids, Integer[] seq, RedirectAttributes redirectAttributes) {
        for (int i = 0; i < ids.length; i++) {
            SysMenu sysMenu = new SysMenu(ids[i]);
            sysMenu.setOrderNum(seq[i]);
            sysMenuService.updateSort(sysMenu);
            // 清除用户菜单缓存
            UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
            // 清除日志相关缓存
            CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
        }
        addMessage(redirectAttributes, "保存菜单排序成功!");
        return "redirect:list";
    }

    /**
     * isShowHide是否显示隐藏菜单
     *
     * @param extId
     * @param isShowHide
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String isShowHide, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<SysMenu> list = UserUtils.getMenuList();
        for (int i = 0; i < list.size(); i++) {
            SysMenu e = list.get(i);

            if (StringUtil.isBlank(extId) || (extId != null && !extId.equals(e.getMenuId() + "") && e.getPerms().indexOf("," + extId + ",") == -1)) {
                if (isShowHide != null && isShowHide.equals("0") && !e.getIsShow()) {
                    continue;
                }
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getMenuId());
                map.put("pId", e.getParentId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }
}
